package com.jizi.machine.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author ljj
 * @description
 * @date 2020-10-30
 */
@EnableAsync
@Configuration
public class AsyncConfig {

    @Bean("taskExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("Anno-Executor");

        //获取最大核心线程数
        int processors = Runtime.getRuntime().availableProcessors();

        //我们这个属于io密集型,所以最大线程设置未cpu核心数两倍即可
        threadPoolTaskExecutor.setCorePoolSize(processors);
        threadPoolTaskExecutor.setMaxPoolSize(processors * 2);


        return threadPoolTaskExecutor;
    }

    @Bean("getAsyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置线程池核心数容量
        executor.setCorePoolSize(5);
        // 设置线程池最大数容量
        executor.setMaxPoolSize(20);
        // 设置任务队列长度
        executor.setQueueCapacity(200);
        // 设置线程超时时间
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称前缀
        executor.setThreadNamePrefix("Async-Executor-");

        // 设置任务丢弃后的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
